package at.jsug.topicvoting.gwt1.client.view.table;

import java.util.List;

import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;

abstract class AbstractTable<E> extends FlexTable {

	private static final int SKIP_HEADER_ROWS_CNT = 1;
		
	private final ITableColumnModel<E> columnModel;
	
	public AbstractTable(final ITableColumnModel<E> columnModel) {
		this.columnModel = columnModel;
		
	    this.setCellPadding(0);
	    this.setCellSpacing(2);
	    	    
	    this.initHeader();
	    

	    //  g.getCellFormatter().setWidth(0, 2, "256px");
	    
	}

	private void initHeader() {
		for (int col = 0; col < this.columnModel.count(); col++) {
    		final Label headerLabel = new Label(this.columnModel.get(col).getHeaderText());
    		headerLabel.setStylePrimaryName("headerTextTopicsGrid");
    		
    		this.setWidget(0, col, headerLabel);
		}
		// this.getFlexCellFormatter().setColSpan(1, 0, COLUMNS_LENGTH);
	}
	

	protected final void addTableRows(List<E> entities) {
		int row = -1;
	    for (E entity : entities) {
	    	row++;
	    	
	    	for (int col = 0; col < this.columnModel.count(); col++) {
	    		// this.setText(row + SKIP_HEADER_ROWS_CNT, col, COLUMNS.get(col).renderAsString(topic));
	    		this.columnModel.get(col).autoRenderOn(this, row + SKIP_HEADER_ROWS_CNT, col, entity);
			}
		}
	}
	
	protected final void clearAllRows() { // except header
		final int n = this.getRowCount();
		for (int i = SKIP_HEADER_ROWS_CNT; i < n; i++) {
			this.removeRow(1);
		}
	}

	protected final void resetTableRows(List<E> entities) {
		System.out.println("AbstractTable.resetTableRows(entities.length="+entities.size()+")");
		this.clearAllRows();
		
		this.addTableRows(entities);
	}
	
	
	public interface ITableColumnModel<E> {
		
		int count();
		
		ITableColumnRenderer<E> get(int index);
		
	}
}
